package handle

import (
	"comic-mgmt-sys/cache"
	"comic-mgmt-sys/model"
	"comic-mgmt-sys/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Logins(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user model.User
	redis_key := "logins_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
	}
	err := model.DB.Where("username=?", username).First(&model.User{})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找失败",
		})
		return
	}
	if user.ID == 0 {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, "3", time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁账户",
			})
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
		"msg":  "登录成功",
	})
	return
}
func UserOrder(c *gin.Context) {
	uid := c.Query("uid")
	var user model.Role
	//SELECT
	//  *
	//FROM
	//  roles
	//  LEFT JOIN user_roles ON roles.id = user_roles.rid
	//  WHERE user_roles.id=1
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
	})
	return
}
func OrderNode(c *gin.Context) {
	nid := c.Query("nid")
	var user model.Node
	//SELECT
	//  *
	//FROM
	//  nodes
	//  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
	//  WHERE role_nodes.id=1
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where(" role_nodes.id = ?", nid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
	})
	return
}
